package per.yhh.xxxtsj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import per.yhh.xxxtsj.entity.PageResult;
import per.yhh.xxxtsj.entity.User;
import per.yhh.xxxtsj.mapper.UserMapper;
import per.yhh.xxxtsj.service.UserService;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yhh
 * @since 2022-04-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    final
    UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public PageResult<User> getUsersByPageAndKey(String keyword, Integer num, Integer size) {
        size = Math.min(size, 10);
        num = Math.max(num, 1);
        Page<User> page = new Page<>(num, size);
        QueryWrapper<User> queryWrapper = null;
        if (!Objects.equals(keyword, "")) {
            queryWrapper = new QueryWrapper<User>();
            queryWrapper.like("nick_name", keyword)
                    .or()
                    .like("account", keyword)
                    .or()
                    .eq("uid", keyword);
        }
        Page<User> UserPage = userMapper.selectPage(page, queryWrapper);
        System.out.println(UserPage.getRecords().size());
        return new PageResult<>(UserPage.getRecords(), UserPage.getPages());
    }

    @Override
    public boolean addUser(User user) {
        int insert = userMapper.insert(user);
        return insert == 1;
    }

    @Override
    public User getUser(Integer uid) {
        return userMapper.selectById(uid);
    }

    @Override
    public User getUserByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean setPermission(Integer uid, Integer value) {
        User user = new User();
        user.setUid(Long.valueOf(uid));
        user.setPermissions(value);
        int i = userMapper.updateById(user);
        return i == 1;
    }

    @Override
    public User login(String account, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        queryWrapper.eq("password",password);
        return userMapper.selectOne(queryWrapper);
    }
}
